package com.chucang.shucang.oms.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.chucang.shucang.common.base.page.PageData;
import com.chucang.shucang.common.base.utils.R;
import com.chucang.shucang.common.mq.constant.RabbitConstant;
import com.chucang.shucang.common.security.annotation.Inner;
import com.chucang.shucang.oms.service.BaseOrderService;
import com.chucang.shucang.oms.vo.AliPayAsyncVO;
import com.chucang.shucang.oms.vo.BaseOrderPageResVO;
import com.chucang.shucang.oms.vo.query.BaseOrderQuery;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/10/6 17:45
 * @description 订单分页聚合
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/baseorder")
public class BaseOrderController {

    private final BaseOrderService baseOrderService;
    private final RabbitTemplate rabbitTemplate;

    @Value("${pay.alipay.aliCert}")
    private String aliCert;

    /**
     * 订单分页
     *
     * @param baseOrderQuery boq
     * @return r
     */
    @PostMapping("/orderPage")
    public R<PageData<BaseOrderPageResVO>> orderPage(@Valid @RequestBody BaseOrderQuery baseOrderQuery) throws ExecutionException, InterruptedException {
        PageData<BaseOrderPageResVO> pageData = baseOrderService.orderPage(baseOrderQuery);
        return R.ok(pageData);
    }

    /**
     * @param aliPayAsyncVO vo
     * @param request       r
     * @return s
     * @throws AlipayApiException e
     */
    @Inner(value = false)
    @PostMapping("/alipay/notify")
    public String aliPayNotify(AliPayAsyncVO aliPayAsyncVO, HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean flag = AlipaySignature.rsaCertCheckV1(params, aliCert, "UTF-8", "RSA2");
        if (flag) {
            if (aliPayAsyncVO.getTrade_status().equals("TRADE_SUCCESS") || aliPayAsyncVO.getTrade_status().equals("TRADE_FINISHED")) {
                //支付成功，先更改账单和订单状态
                //订单类型 0藏品 1盲盒 2充值 其中藏品和盲盒的订单一定是orderSn没有生成账单 充值订单是billSn有生成账单
                String type = aliPayAsyncVO.getPassback_params();
                if (type.equals("0")) {
                    //藏品订单处理
                    //如果是一级市场购买藏品 批量上链，二级市场则只改归属，藏品所属链转移
                    rabbitTemplate.convertAndSend(RabbitConstant.PAY_EXCHANGE, RabbitConstant.ALIPAY_COLLECTION_SUCCESS_KEY, aliPayAsyncVO.getOut_trade_no());
                } else if (type.equals("1")) {
                    //盲盒订单处理
                    //如果是二级市场购买盲盒 藏品转移，更改归属
                    rabbitTemplate.convertAndSend(RabbitConstant.PAY_EXCHANGE, RabbitConstant.ALIPAY_BLIND_BOX_SUCCESS_KEY, aliPayAsyncVO.getOut_trade_no());
                } else if (type.equals("2")) {
                    //如果是充值订单，钱包充值，更改账单状态
                    rabbitTemplate.convertAndSend(RabbitConstant.PAY_EXCHANGE, RabbitConstant.ALIPAY_RECHARGE_SUCCESS_KEY, aliPayAsyncVO.getOut_trade_no());
                }
            }
            return "success";
        } else {
            return "fail";
        }
    }
}
